<template>
  <div class="supplier" v-loading="loading">
    <div v-if="editShow" style="margin-top: 20px">
      <Button type="primary" label="编辑" @click="onEditClick" />
      <div v-if="editLevelData.statusData.operateType" class="search-text"
           :style="{'background-color': styleFun('background')}">
        <span :style="{'color': styleFun('color')}">{{ styleFun('text') }}</span>
        <Link @click="onLookClick" label="查看" :underline="false" />
      </div>
    </div>
    <div v-else style="margin-top: 20px">
      <Button @click="saveEditClick" type="primary" label="保存" />
      <Button @click="onCancelClick" type="primary" label="取消" />
      <Button label="添加会员等级" @click="onAddClick" />
    </div>

    <el-table v-if="editShow" :height="tableHeight" ref="tableRef" :data="editLevelData.memberDataList">
      <el-table-column fixed="left" type="index" label="序号" width="80" />
      <el-table-column label="会员等级名称" prop="memberName" />
      <el-table-column label="折扣比例" prop="discountRate">
        <template #default="{row}">
          <div>{{ row.discountRate / 100 }}%</div>
        </template>
      </el-table-column>
      <!-- 这个表格 -->
      <el-table-column prop="memberItemList" label="参与采购商">
        <template #default="{row}">
          <div class="memberNameStyle">
            <el-tag v-if="row.memberItemList.length >= 1" style="margin-right: 40px">
              {{ row.memberItemList[0].customerName }}
            </el-tag>
            <el-tooltip placement="left" effect="light">
              <template #content>
                <div class="scrollStyle">
                  <el-scrollbar height="400px">
                    <div class="tooltipTitle">会员名称</div>
                    <div class="tooltipStyle">
                      <div v-for="(item) in row.memberItemList" style="margin: 10px 0">
                        <img src="@/assets/images/paixu.png" />
                        <el-tag style="margin-left: 10px">{{ item.customerName }}</el-tag>
                      </div>
                    </div>
                  </el-scrollbar>
                </div>
              </template>
              <img v-show="row.memberItemList.length > 1" src="@/assets/images/bottom.png" />
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-table v-else :height="tableHeight" ref="tableRef" :data="editLevelData.saveMemberData">
      <el-table-column label="会员等级名称" prop="memberName" width="300px">
        <template #default="{row,$index}">
          <el-input :disabled="$index === 0" v-model="row.memberName"></el-input>
        </template>
      </el-table-column>

      <el-table-column label="折扣比例" prop="discountRate" width="300px">
        <template #default="{row,$index}">
          <div style="display: flex;align-items: center">
            <el-input :disabled="$index === 0" v-model="row.discountRate"></el-input>
            <div style="margin-left: 10px">%</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="memberItemList" label="参与采购商">
        <template #default="{row,$index}">
          <div style="display: flex;justify-content: space-between">
            <div class="memberTagStyle">
              <el-tag v-for="(item) in row.memberItemList" style="margin: 3px">{{ item.customerName }}</el-tag>
            </div>
            <div>
              <img v-show="$index !== 0" v-if="row.memberItemList.length >= 1"
                   @click="onSelectCustomer(row,$index)"
                   src="@/assets/images/bianji.png" />
              <Link :disabled="$index === 0" v-else @click="onSelectCustomer(row,$index)" label="选择采购商"
                    :underline="false" />
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" v-if="!editShow" width="120">
        <template #default="{row,$index}">
          <Link :disabled="$index === 0" @click="onDeleteClick(row)" label="删除" :underline="false" />
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="lookAuditDialog" :close-on-click-modal="false">
    <div class="detailDialog">审核进度</div>
    <div class="search-text" :style="{'background-color': styleFun('background')}">
      <span :style="{'color': styleFun('color')}">
      {{ styleFun('text') }}
        <span v-if="editLevelData.statusData.operateType === 'REJECT' " style="margin-left: 30px">
          驳回原因： {{ editLevelData.statusData.remark }}
        </span>
      </span>
    </div>
    <div>
    </div>

    <table class="table">
      <thead class="table_header_title">
      <tr>
        <th style="width: 50px">序号</th>
        <th style="width: 200px">会员等级名称</th>
        <th style="width: 200px">折扣比例</th>
        <th>参与采购商</th>
      </tr>
      </thead>
      <tbody class="table_tbody">
      <tr class="goods" v-for="(goods,index) in editLevelData.auditData" :key="goods.id">
        <td>
          <div class="goods-info"><span> {{ index + 1 }}</span></div>
        </td>
        <td>
          <span> {{ goods.memberName }}</span>
        </td>
        <td>
          <span> {{ goods.discountRate / 100 }}</span>
        </td>
        <td>
          <div style="display: flex;justify-content: space-between">
            <div ref="examineDialogRef" class="examineDialogStyle">
              <el-tag class="curBox" v-for="goodItem in goods.memberItemList">{{ goodItem.customerName }}</el-tag>
            </div>
            <el-tooltip placement="left" effect="light">
              <template #content>
                <div class="scrollStyle">
                  <div class="tooltipTitle">会员名称</div>
                  <div class="tooltipStyle">
                    <div v-for="(item) in goods.memberItemList" style="margin: 10px 0">
                      <img src="@/assets/images/paixu.png" />
                      <el-tag style="margin-left: 10px">{{ item.customerName }}</el-tag>
                    </div>
                  </div>
                </div>
              </template>
              <img ref="imgDialogRef" style="width: 10px ;height: 10px" src="@/assets/images/bottom.png" />
            </el-tooltip>
          </div>
        </td>
      </tr>
      </tbody>
    </table>
  </el-dialog>

  <el-dialog v-model="dialogEditVisible" :close-on-click-modal="false"
             :show-close="false" :close-on-press-escape="false">
    <div class="detailDialog">{{ editLevelData.editDialogData.memberName }} -
      折扣{{ editLevelData.editDialogData.discountRate }}%
    </div>

    <div>
      <el-row>
        <el-col :span="12">
          <div style="width: 100%;height: 500px">
            <el-scrollbar height="500px">
              <el-table :data="editLevelData.allCustomerList" highlight-current-row ref="multipleTableRef"
                        style="width: 100%">
                <el-table-column width="55">
                  <template #default="{row}">
                    <el-checkbox v-model="row.check" @change="handleCheckAllChange(row)"></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column prop="customerName" label="采购商列表">
                  <template #default="{row}">
                    <div style="display: flex;align-items: center">
                      <div>{{ row.customerName }}</div>
                      <el-tag style="margin-left: 10px" v-show="row.editReason" type="success">
                        {{ row.editReason ? '已选' : '未选' }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-scrollbar>
          </div>
        </el-col>

        <el-col :span="11" style="margin-left: 10px">
          <div style="width: 100%;height: 500px">
            <el-scrollbar height="500px">
              <el-table :data="editLevelData.selectCustomer" stripe highlight-current-row
                        style="width: 100%">
                <el-table-column prop="customerName" label="Date">
                  <template #header>
                    <div class="editDialogTable">
                      <div>已选{{ editLevelData.selectCustomer.length }}项</div>
                    </div>
                  </template>
                  <template #default="{row}">
                    <div class="editDialogTable">
                      <div class="editDialogTable">
                        <img src="@/assets/images/paixu.png" />
                        <div style="margin-left: 10px">{{ row.customerName }}</div>
                      </div>
                      <Link label="删除" @click="onClearSelectClick(row)" :underline="false" />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <Button type="primary" @click="dialogEditVisible = false" label="取消" />
      <Button type="primary" @click="onSureClick" label="确定" />
    </template>
  </el-dialog>

</template>
<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { calcTableHeight } from '@/assets/js/utils.js'
import Link from '@/components/button/link.vue'
import Button from '@/components/button/button.vue'
import { useRoute } from 'vue-router'
/********************************/
const route = useRoute()
const { tableRef, tableHeight } = calcTableHeight(650)
const editShow = ref(true)
const examineDialogRef = ref(null)
const imgDialogRef = ref(null)
const lookAuditDialog = ref(false)
const dialogEditVisible = ref(false)
const loading = ref(false)
const editLevelData = reactive({
  // COMMIT 审核中 REJECT 被驳回 PASS 已通过
  supplierId: route.params.id,// 供应商id
  statusData: {}, // 审核状态
  auditData: [], // 待审核的会员等级信息
  memberDataList: [], // 会员等级列表
  saveMemberData: [], // 保存的会员等级信息
  allCustomerList: [], // 所有的采购商列表

  editDialogData: {}, // 编辑参与的采购商
  editDialogReason: [], // 已经存在会员等级的采购商
  selectCustomer: [] // 保存选中的采购商
})

const handleCheckAllChange = (row) => {
  if (row.check) {  // 选中
    console.log('row', row)
    editLevelData.selectCustomer.push(row)
  } else {
    editLevelData.selectCustomer = editLevelData.selectCustomer.filter(item => item.customerId !== row.customerId)
  }
}
const onClearSelectClick = (row) => {
  editLevelData.selectCustomer = editLevelData.selectCustomer.filter(item => item.customerId !== row.customerId)
  editLevelData.allCustomerList.forEach(item => {
    if (item.customerId === row.customerId) {
      item.check = false
    }
  })
}
const onLookClick = () => {
  lookAuditDialog.value = true
  nextTick(() => {
    for (let i = 0; i < examineDialogRef.value.length; i++) {
      if (examineDialogRef.value[i].scrollHeight === examineDialogRef.value[i].clientHeight) {
        // console.log('需要隐藏元素', i)
        imgDialogRef.value[i].style.display = 'none'  // 隐藏元素
      } else {
        // console.log('不需要隐藏元素', i)
      }
    }
  })
}

const onSureClick = () => {
  // 点击确定按钮的时候需要将当前选中的 添加到当前的会员等级当中 并且将其他的会员等级中的该采购商删除掉
  editLevelData.saveMemberData.forEach(item => {
    item.memberItemList = item.memberItemList.filter(memberItem => {
      const isDelete = editLevelData.selectCustomer.some(item2 => item2.customerId === memberItem.customerId)
      return !isDelete
    })
    // editDialogData 当前编辑的会员等级
    if (editLevelData.editDialogData.id === item.id) {
      item.memberItemList = []
      item.memberItemList.push(...editLevelData.selectCustomer)
    }
  })
  editLevelData.editDialogReason = editLevelData.editDialogReason.filter(selectItem => {
    // 如果不存在该采购商 那么将该采购商添加到
    const isExist = editLevelData.editDialogData.memberItemList.some(item2 => item2.customerId === selectItem.customerId)
    return !isExist
  })
  editLevelData.editDialogReason.push(...editLevelData.selectCustomer)
  dialogEditVisible.value = false
}
// 保存
const saveEditClick = async () => {
  // if (editLevelData.saveMemberData.length !== 5) {
  //   ElMessage.error('会员等级最多5级')
  //   return
  // }
  const nameRequired = editLevelData.saveMemberData.some(item => {
    return String(item.memberName).trim() === '' || String(item.discountRate).trim() === ''
  })
  if (nameRequired) {
    ElMessage.error('会员等级名称或折扣比例不能为空')
    return
  }
  const params = []
  const id = editLevelData.saveMemberData[0].supplierId
  // 提交的数据
  editLevelData.saveMemberData.forEach(item => {
    const customerIds = []
    item.memberItemList.forEach(memberItem => {
      customerIds.push(memberItem.customerId)
    })
    params.push({
      customerIds,
      discountRate: Number(item.discountRate) * 100,
      memberName: item.memberName,
      supplierId: id
    })
  })
  const { data, err } = await api.post('/medinstrument/boss/member/save', params)
  if (err) {
    ElMessage.error('操作失败')
    loadData()
    return
  } else {
    ElMessage({
      type: 'success',
      message: '保存成功'
    })
    loadData()
  }
  editShow.value = true
}

const onDeleteClick = (row) => {
  if (row.discountRate === '' && row.memberName === '' && row.memberItemList.length === 0) {
    editLevelData.saveMemberData = editLevelData.saveMemberData.filter(item => item.id !== row.id)
    return
  }
  ElMessageBox.confirm(
    `是否确认删除 ${row.memberName} 会员等级`,
    '提示',
    {
      distinguishCancelAndClose: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      editLevelData.saveMemberData = editLevelData.saveMemberData.filter(item => item.id !== row.id)
      // 这个时候需要将其中的采购商 重新分配给默认的会员等级
      editLevelData.editDialogReason = editLevelData.editDialogReason.filter(item => {
        return !row.memberItemList.some(item2 => item2.id === item.id)
      })
    })
    .catch((action) => {
    })
}
// status:  1已通过 PASS 2审核中 AUDITING 3被驳回 REJECTED 待审核 WAITING_AUDIT
const onEditClick = () => {
  editLevelData.saveMemberData = JSON.parse(JSON.stringify(editLevelData.memberDataList))
  // 折扣率出现小数点后两位
  editLevelData.saveMemberData.forEach(item => {
    item.discountRate = item.discountRate / 100
  })
  editShow.value = false
}
const onCancelClick = () => {
  editShow.value = true
}

const onAddClick = () => {
  if (editLevelData.saveMemberData.length >= 5) {
    ElMessage.error('会员等级最多为5个')
    return
  }
  editLevelData.saveMemberData.push({
    id: Math.random().toString(36).slice(2),
    discountRate: '',
    memberName: '',
    memberItemList: []
  })
}

const onSelectCustomer = (row) => {
  editLevelData.allCustomerList.forEach(item => {
    item.check = false
    item.editReason = ''
    // 其他的采购商中存在该会员等级
    const isReason = editLevelData.editDialogReason.some(item2 => item2.customerId === item.customerId)
    // 找出本身拥有的采购商
    const isCheck = row.memberItemList.some(item2 => item2.customerId === item.customerId)
    // 其他的采购商存在的会员等级
    if (isCheck) {
      item.check = true
    }
    if (isReason && !isCheck) {
      item.editReason = item.customerName
    }
  })
  editLevelData.editDialogData = JSON.parse(JSON.stringify(row))
  editLevelData.selectCustomer = JSON.parse(JSON.stringify(row.memberItemList))
  dialogEditVisible.value = true
}

/********************************/

const loadData = async () => {
  loading.value = true
  // 查看待审核会员等级详情
  let {
    data,
    err
  } = await api.get(`/medinstrument/boss/member/getApplyMemberList?supplierId=${editLevelData.supplierId}`)  // 获取待审核会员状态
  // 会员等级详情
  let memberList = await api.get(`/medinstrument/boss/member/getMemberList?supplierId=${editLevelData.supplierId}`) // 获取会员列表
  // 所有的采购商列表
  let customerList = await api.get(`/medinstrument/boss/customer/allCustomerList`) // 获取所有的采购商
  if (err) {
    ElMessage.error(err)
    return
  }
  editLevelData.memberDataList = memberList.data
  editLevelData.allCustomerList = customerList.data.list
  editLevelData.memberDataList.forEach(item => {
    editLevelData.editDialogReason.push(...item.memberItemList)
  })
  // 待审核的会员等级信息可能有多个，默认取第一个 也可能为空
  if (data.operateList.length > 0) {
    editLevelData.statusData = data.operateList[0]
  }
  editLevelData.auditData = data.memberList
  loading.value = false
}

const styleFun = (prop) => {
  const status = editLevelData.statusData.operateType
  if (prop === 'text') {
    return status === 'PASS' ? '已通过' : status === 'COMMIT' ? '审核中' : status === 'REJECT' ? '被驳回' : '待审核'
  } else if (prop === 'color') {
    return status === 'PASS' ? '#67C23A' : status === 'COMMIT' ? '#E6A23C' : status === 'REJECT' ? '#F56C6C' : '#FEF0F0'
  } else if (prop === 'background') {
    return status === 'PASS' ? '#F0F9EB' : status === 'COMMIT' ? '#FDF6EC' : status === 'REJECT'
      ? '#FEF0F0' : '#909399'
  }
}

onMounted(async () => {
  await loadData()
})
defineExpose({
  loadData
})
</script>
<style lang="scss" scoped>
.memberTagStyle {
  box-sizing: border-box;
  width: calc(100% - 100px);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.examineDialogStyle {
  box-sizing: border-box;
  display: flex;
  width: calc(100% - 60px);
  flex-wrap: wrap;
  text-overflow: ellipsis;
  overflow: hidden;
  min-height: 32px;
  max-height: 62px;

  .curBox {
    margin: 3px;
  }
}

.table {
  border-collapse: collapse;
  width: 100%;

  th {
    background: #FAFAFA;
    height: 48px;
  }

  .table_header_title {
    height: 30px;
    color: #909399;
  }

  .table_tbody {
    tr {
      height: 49px;

      td {
        line-height: 18px;
        text-align: center;
        border-bottom: 1px solid #ccc;
        padding: 5px;
      }

      .amountStyle {
        box-sizing: border-box;
        display: flex;
        width: 160px;
        background-color: red;
        flex-wrap: wrap;
        overflow: hidden;
        min-height: 20px;
        max-height: 50px;
      }
    }
  }
}

.search-text {
  height: 34px;
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;

  span {
    font-size: 15px;
    letter-spacing: 0;
    line-height: 16px;
    font-weight: 500;
  }
}

.detailDialog {
  font-size: 18px;
  color: #303133;
  font-weight: 600;
  margin-bottom: 20px;
}

.editDialogTable {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

</style>
